from django.conf import settings
from public.constants import logger
import requests

config = settings.SERVICES['JPUSH']


def push(message, audience, extras=None, platform='all'):
    """
    极光推送通知，接口文档 https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/
    :param message: 通知内容
    :param audience: 通知对象，'all' 全体推送，{'alias: []} 通过别名推送，{'registration_id': []} 注册ID推送，参考文档 https://docs.jiguang.cn/jpush/server/push/rest_api_v3_push/#audience
    :param extras: 通知附加信息，会传递给app
    :param platform: 按平台推送，'all' 全平台，'android' | 'ios' | 'winphone'
    :return: None
    """
    try:
        assert audience == 'all' or isinstance(audience, dict)
        body = {
            'platform': platform,
            'audience': audience,
            'notification': {
                'alert': message,
            }
        }
        if extras:
            assert isinstance(extras, dict)
            body['notification']['android'] = {'extras': extras}
            body['notification']['ios'] = {'extras': extras}
        auth = (config['APP_KEY'], config['APP_SECRET'])
        res = requests.post('https://api.jpush.cn/v3/push', json=body, auth=auth).json()
        if res.get('error'):
            logger.error(f'JPush error: {res}')
    except Exception as e:
        logger.exception(f'JPush error {e}')
        raise e
